/*
 * @Description: 描述
 * @Author: liym
 * @Date: 2025-05-08 20:34:26
 * @LastEditors: liym
 * @LastEditTime: 2025-05-12 09:26:20
 */
// common/request.js

import config from '../config'
import { logout } from './util.js'
const conf = config.getEnv();
const BASE_URL = conf.API_BASE_URL  // 这里换成你的后端地址

// 核心请求方法
const httpRequest = (url, method, data = {}, header = {}) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': uni.getStorageSync('token') || '',
        ...header
      },
      success: res => {
        // console.log(res)
		    const resData = res.data
        if (res.statusCode === 200 && resData.code === 200) {
          resolve(resData)
        } else {
          
          if (resData.code === 401) {
            logout()
          } else {
            uni.showToast({
              title: resData.message || '请求失败',
              icon: 'none',
            })
          }
          
          reject(resData)
        }
      },
      fail: err => {
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 封装 GET 和 POST 方法
const request = {
  get: (url, data = {}, header = {}) => httpRequest(url, 'GET', data, header),
  delete: (url, data = {}, header = {}) => httpRequest(url, 'DELETE', data, header),
  post: (url, data = {}, header = {}) => httpRequest(url, 'POST', data, header),
}

export default request
